package com.jkdz.spyke.widgetUIs {
	import com.jkdz.spyke.flexUI.helpers.Link;
	import com.jkdz.spyke.flexUI.helpers.SuperWindow;
	import com.jkdz.spyke.flexUI.main.Main;
	import com.jkdz.spyke.rs.SpykeURLDisplay;
	import com.jkdz.spyke.rs.SpykeURLDisplayListener;
	import com.jkdz.spyke.rs.SpykeWidget;
	import com.jkdz.spyke.rs.SpykeWidgetConstructor;
	
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.system.System;
	
	import mx.controls.TextInput;
	import mx.core.FlexGlobals;
	import mx.events.FlexEvent;
	
	import spark.components.Button;
	import spark.components.Form;
	import spark.components.FormItem;
	import spark.components.Group;
	import spark.layouts.HorizontalAlign;
	import spark.layouts.HorizontalLayout;
	import spark.layouts.VerticalAlign;
	import spark.layouts.VerticalLayout;
	
	public class SpykeWidgetConstructorUI extends SpykeWidgetUI {
		
		private var widget:SpykeWidgetConstructor;
		private var window:SuperWindow;
		
		public function SpykeWidgetConstructorUI(widget:SpykeWidgetConstructor) {
			this.widget = widget;
		}
		
		override public function display(onComplete:Function):void {			
			widget.getAvailableWidgets(function(names:Vector.<*>):void {
				showUI(names, onComplete);
			});
		}
		
		private function showUI(names:*, onComplete:Function):void {

			var hl:VerticalLayout = new VerticalLayout();
			hl.gap = 10;
			hl.horizontalAlign = HorizontalAlign.CENTER;
			hl.paddingBottom = hl.paddingTop = hl.paddingRight = hl.paddingLeft = 10;
			this.layout = hl;

			for each (var name:String in names) {
				var createLink:Link = new Link(name+" Widget");
				createLink.addEventListener(MouseEvent.CLICK, function(actualName:String):Function {
					return function(e:MouseEvent):void {
						var widgetUIClass:Class = Main.getUIClassForName(actualName);
						if (!widgetUIClass.hasOwnProperty("canOwn") || widgetUIClass.canOwn()) {
							SuperWindow.progress("Creating a "+actualName+" widget...", true);
							widget.createNewWidget(actualName, function(newWidget:SpykeWidget):void {
								if (widgetUIClass.hasOwnProperty("own")) {
									widgetUIClass.own(newWidget);
								}
								newWidget.publish();
							});
						}
					};
				}(name));
				createLink.toolTip = "Create the "+name+" widget.";
				this.addElement(createLink);
			}
			
			this.window = SuperWindow.display(FlexGlobals.topLevelApplication as Main, this, "Available widgets", false, false, true, false);
			this.window.x = (FlexGlobals.topLevelApplication as Main).width-10-this.window.width;
			this.window.y = (FlexGlobals.topLevelApplication as Main).height-10-this.window.height;
			onComplete();
		}

	}
}